package com.OptionalTest;

import java.util.Optional;

/**
 *
 * 为了在程序中避免空指针异常而出现的Optional
 *
 * 常用方法 Optional.of(Object o);
 *        Optional.ofNullable(Object o);
 *
 *
 * @Auther: MFM
 * @Date: 2022/3/2 - 03 - 02 - 16:43
 * @version: 1.0
 */

public class OptionalTest {
    public void test1(){
        Girl girl = new Girl();
        Optional<Girl> optionalGirl = Optional.of(girl);
    }

    public void test2(){
        Girl girl = new Girl();
        girl=null;
        //ofNullable传入的value可以为空
        Optional<Girl> girl1 = Optional.ofNullable(girl);
        System.out.println(girl1);
    }

    public void test3(){
        Boy boy = new Boy();
        String name = getGirlName(boy);//报错 空指针异常
        System.out.println(name);
    }

    public String getGirlName(Boy boy){
        return boy.getGirl().getName();
    }

    //优化以后的getGirlName方法
    public String reGetGirlName(Boy boy){
        if (boy!=null){
            if (boy.getGirl()!=null){
                //运行时不会有空指针异常问题
                return boy.getGirl().getName();
            }
        }
        return null;
    }

    //使用Optional类的getGirlName
    public String newGetGirlName(Boy boy){
        Optional<Boy> boy1 = Optional.ofNullable(boy);

        //如果boy1有东西就返回boy1 如果没有就用（）里面的备胎
        Boy boy2 = boy1.orElse(new Boy(new Girl("哈哈")));
        return boy2.getGirl().getName();
    }

    public static void main(String[] args) {
        new OptionalTest().test3();
    }
}
